//
//  XJUserAccountViewModel.m
//  weiboOC
//
//  Created by 徐绩 on 16/4/21.
//  Copyright © 2016年 ayumi. All rights reserved.
//

#import "XJUserAccountViewModel.h"
#import "XJNetworkTools.h"
#import "XJUserAccountModel.h"

@implementation XJUserAccountViewModel

+(instancetype)sharedViewModel{

    static XJUserAccountViewModel *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc]init];
    });
    return instance;
}

-(instancetype)init{

    if (self = [super init]) {
        //初始化时解档数据
        self.accout = [self userAccoutInSandbox];
    }
    return self;
}

/**
 *  判断用户是否登录:1.是否有授权码   2.授权码是否过期
 */
-(BOOL)isLogin{
    
    NSString *accessToken = self.accout.access_token;
    
    if (accessToken == nil) {
        return NO;
    }
    
    NSDate *expiresDate = self.accout.expiresDate;
    
    if (expiresDate == nil) {
        return NO;
        
    }else if ([[NSDate date] compare:expiresDate] == NSOrderedAscending){
    
        return YES;
    }
    return NO;
}

-(void)loadAccessToken:(NSString *)code isSuccess:(void (^)(BOOL))finishedBlock{

    NSString *url = @"https://api.weibo.com/oauth2/access_token";
  
    NSDictionary *param = @{@"client_id":@"3663247462",
                                 @"client_secret":@"b87e34ba9aefdfcca7e4d0fbaf45862e",
                                 @"grant_type":@"authorization_code",
                                 @"code":code,
                                 @"redirect_uri":@"http://www.baidu.com/"
                                 };

    [[XJNetworkTools sharedTools]request:XJRequestMethodPost urlString:url parameters:param finished:^(NSDictionary * responseObject, NSError *error) {
        
        if (error) {
            Log(@"%@",error);
            finishedBlock(NO);
            return;
        }
            //字典转模型
            XJUserAccountModel *model = [XJUserAccountModel accountModelWithDict:responseObject];
        
        [self loadUserInfo:model isSuccess:^(BOOL isSuccess) {
            finishedBlock(isSuccess);
        }];

    }];
}

#pragma mark - 获取个人信息
-(void)loadUserInfo:(XJUserAccountModel *)account isSuccess:(void (^)(BOOL))finishedBlock{
 
    NSString *url = @"https://api.weibo.com/2/users/show.json";
    
    NSDictionary *params = @{
                            @"access_token":account.access_token,
                            @"uid":account.uid
                            };
    
    [[XJNetworkTools sharedTools]request:XJRequestMethodGet urlString:url parameters:params finished:^(NSDictionary * responseObject, NSError *error) {
        
        if (error) {
            finishedBlock(NO);
            return;
        }
        account.name = responseObject[@"name"];
        account.avatar_large = responseObject[@"avatar_large"];
        
        self.accout = account;
        
        [self saveUserInfo:account];
        
        finishedBlock(YES);
    }];

}

#pragma mark - 保存用户信息
-(void)saveUserInfo:(XJUserAccountModel *)userAccount{

    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"account.archive"];
    
    [NSKeyedArchiver archiveRootObject:userAccount toFile:path];
}

#pragma mark - 读取用户登录信息
-(XJUserAccountModel *)userAccoutInSandbox{

    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"account.archive"];
    
   XJUserAccountModel *model = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    
    return model;

}

@end
